#include "stdafx.h"
#include "FileLoader.h"

#include <NezhaIFileSystem.h>

using namespace Nezha;
using namespace stream;

cFileLoader::cFileLoader()
{
	mMemUsed = false;
	mReadFile = 0;
}

cFileLoader::~cFileLoader()
{
	Close();
}

bool cFileLoader::Open( const _string& pathName, bool useMemory )
{

	IFileSystem* fileSystem = IFileSystem::GetInterface();
	
	bool isExist  = fileSystem->existFile(pathName);

	if( isExist )
	{
		mReadFile = fileSystem->createReadFile(pathName.c_str());

		if( !mReadFile)
		{
			assert( 0 && "file is open error!!" );
			return false;
		}
	}
	
	mMemUsed = useMemory;

	return mReadFile != 0;
}

bool cFileLoader::OpenNoPack( const _string& pathName, bool useMemory )
{
	return false;
}

int cFileLoader::Close()
{
	mMemUsed = false;

	if( mReadFile )
	{
		//int ret = mReadFile->close();
		delete mReadFile;
		mReadFile = 0;
		//return ret;
	}
	return 0;
}

unsigned int cFileLoader::Read( void* buffer, unsigned int size )
{
	if( mReadFile )
	{
		return mReadFile->read( buffer, size );
	}
	return 0;
}

bool cFileLoader::ReadInt( int* pvalue )
{
	if( mReadFile )
	{
		return mReadFile->read( pvalue, sizeof(int) ) == sizeof(int);
	}
	return false;
}

bool cFileLoader::ReadUnsignedInt( unsigned int* pvalue )
{
	if( mReadFile )
	{
		return mReadFile->read( pvalue, sizeof(unsigned int) ) == sizeof(unsigned int);
	}
	return false;
}

bool cFileLoader::ReadFloat( float* pvalue )
{
	if( mReadFile )
	{
		return mReadFile->read( pvalue, sizeof(float) ) == sizeof(float);
	}
	return false;
}

unsigned int cFileLoader::ReadLine( char* buffer, unsigned int bufferSize )
{
	if( mReadFile )
	{
		//return mReadFile->ReadLine( buffer, bufferSize );
	}
	return 0;
}

int cFileLoader::Seek( unsigned int offset, int origin )
{
	if( mReadFile )
	{
		return mReadFile->seek( offset );
	}
	return -1;
}

unsigned int cFileLoader::Tell() const
{
	if( mReadFile )
	{
		return mReadFile->getPos();
	}
	return 0;
}

unsigned int cFileLoader::GetSize() const
{
	if( mReadFile )
	{
		return mReadFile->getSize();
	}
	return 0;
}

bool cFileLoader::IsEnd() const
{
	if( mReadFile )
	{
		return mReadFile->getSize() == mReadFile->getPos();
	}
	return true;
}

bool cFileLoader::IsEmpty() const
{
	if( mReadFile )
	{
		return mReadFile->getSize() == 0;
	}
	return true;
}

const char* cFileLoader::GetBufferPtr()
{
	if( mMemUsed && mReadFile )
	{
		long size = 0;

		return (const char*)mReadFile->getBuffer(&size);
	}
	return 0;
}
